package cn.zjitc.controller;

import cn.zjitc.entity.PageResult;
import cn.zjitc.entity.QueryPageBean;
import cn.zjitc.entity.Result;
import cn.zjitc.pojo.Borrow;
import cn.zjitc.pojo.History;
import cn.zjitc.pojo.User;
import cn.zjitc.service.AdminBorrowService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;


@RestController
@RequestMapping("/adminborrow")
public class AdminBorrowController {

    @Reference
    private AdminBorrowService adminBorrowService;

    //还书
    @GetMapping("/add")
    public Result add(Integer id, String name, HttpSession session){
        Date date=new Date();
        try{
            User user = (User) session.getAttribute("user");
            Borrow borrow=new Borrow();
            borrow.setBook_id(id);
            String neoname = new String(name.getBytes("ISO-8859-1"), "UTF-8");
            borrow.setBook_name(neoname);
            borrow.setUser_id(user.getUser_id());
            borrow.setReturn_time(date);
            Integer remainnum=adminBorrowService.findremainnum(id);
            Integer maxnum=adminBorrowService.findmaxnum(id);
            if(remainnum+1<maxnum){
                borrow.setBook_state(1);
                borrow.setBorrow_state(0);
                adminBorrowService.edit(borrow);
                adminBorrowService.editbooklist(id);
            }
            if(remainnum+1==maxnum){
                borrow.setBook_state(1);
                borrow.setBorrow_state(1);
                adminBorrowService.edit(borrow);
                adminBorrowService.editbooklist(id);
            }
            History history=new History();
            history.setUser_id(user.getUser_id());
            history.setBook_id(id);
            history.setReturn_time(date);
            history.setBorrow_state(1);
            adminBorrowService.editHistory(history);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"归还书籍失败");
        }
        return new Result(true,"归还书籍成功");
    }


    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult= adminBorrowService.pageQuery(queryPageBean);
        return pageResult;
    }
}
